package com.example.pt.service;

import com.example.pt.dto.UserFollowDTO;
import com.example.pt.entity.User;
import com.example.pt.entity.UserFollow;
import com.example.pt.mapper.PrivateMessageMapper;
import com.example.pt.mapper.UserFollowMapper;
import com.example.pt.repository.UserRepositories;
import com.example.pt.utils.DownloadUrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户关注服务类
 */
@Service
public class UserFollowService {

    @Autowired
    private UserFollowMapper userFollowMapper;
    
    @Autowired
    private PrivateMessageMapper privateMessageMapper;
    
    @Autowired
    private UserRepositories userRepositories;

    @Autowired
    private DownloadUrlUtils downloadUrlUtils;
    
    /**
     * 获取用户的关注列表
     * @param followerId 关注者ID（当前用户）
     * @return 关注列表
     */
    public List<UserFollowDTO> getFollowingList(Integer followerId) {
        // 获取用户的关注记录
        List<UserFollow> followings = userFollowMapper.selectFollowingsByFollowerId(followerId);
        List<UserFollowDTO> result = new ArrayList<>();
        
        for (UserFollow following : followings) {
            UserFollowDTO dto = new UserFollowDTO();
            dto.setFollowId(following.getFollowId());
            dto.setFollowerId(following.getFollowerId());
            dto.setFollowedId(following.getFollowedId());
            dto.setCreateTime(following.getCreateTime());

            String headShotUrl = downloadUrlUtils.generateDownloadLink(following.getFollowedId());

            dto.setHeadShot(headShotUrl);
            
            // 获取被关注者信息
            User followedUser = userRepositories.findByUid(following.getFollowedId());
            if (followedUser != null) {
                dto.setUsername(followedUser.getUsername());
                dto.setHeadshot(followedUser.getHeadshot());
                dto.setStatus(followedUser.getStatus());
                
                // 生成会话ID
                String conversationId = followerId < following.getFollowedId()
                    ? followerId + "_" + following.getFollowedId()
                    : following.getFollowedId() + "_" + followerId;
                
                // 查询未读消息数
                int unreadCount = privateMessageMapper.countUnreadMessages(followerId, conversationId);
                dto.setUnreadCount(unreadCount);
            }
            
            result.add(dto);
        }
        
        return result;
    }
    
    /**
     * 关注用户
     * @param followerId 关注者ID（当前用户）
     * @param followedId 被关注者ID
     * @return 是否成功
     */
    @Transactional
    public boolean followUser(Integer followerId, Integer followedId) {
        // 检查被关注者是否存在
        User followedUser = userRepositories.findByUid(followedId);
        if (followedUser == null) {
            return false;
        }
        
        // 不能关注自己
        if (followerId.equals(followedId)) {
            return false;
        }
        
        // 检查是否已经关注过
        UserFollow existingFollow = userFollowMapper.selectByFollowerIdAndFollowedId(followerId, followedId);
        
        if (existingFollow == null) {
            // 创建新的关注记录
            UserFollow userFollow = new UserFollow();
            userFollow.setFollowerId(followerId);
            userFollow.setFollowedId(followedId);
            userFollow.setCreateTime(new Date());
            userFollow.setStatus(0); // 0-正常
            userFollowMapper.insert(userFollow);
        } else if (existingFollow.getStatus() == 1) {
            // 已取消的关注，重新关注
            userFollowMapper.refollowUser(followerId, followedId);
        } else {
            // 已经关注，不做处理
            return true;
        }
        
        return true;
    }
    
    /**
     * 取消关注
     * @param followerId 关注者ID（当前用户）
     * @param followedId 被关注者ID
     * @return 是否成功
     */
    @Transactional
    public boolean unfollowUser(Integer followerId, Integer followedId) {
        // 检查是否已关注
        UserFollow existingFollow = userFollowMapper.selectByFollowerIdAndFollowedId(followerId, followedId);
        
        if (existingFollow != null && existingFollow.getStatus() == 0) {
            // 取消关注
            userFollowMapper.unfollowUser(followerId, followedId);
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查是否已关注用户
     * @param followerId 关注者ID（当前用户）
     * @param followedId 被关注者ID
     * @return 是否已关注
     */
    public boolean checkFollowStatus(Integer followerId, Integer followedId) {
        UserFollow existingFollow = userFollowMapper.selectByFollowerIdAndFollowedId(followerId, followedId);
        return existingFollow != null && existingFollow.getStatus() == 0;
    }
} 